#!/usr/bin/env python3
"""
对话处理服务启动脚本
"""

import argparse
import uvicorn
from pathlib import Path
import sys

# 添加项目根目录到 Python 路径
current_dir = Path(__file__).parent
if str(current_dir) not in sys.path:
    sys.path.insert(0, str(current_dir))

from app.core.config import settings
from app.core.logging import setup_logging

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="对话处理服务")
    parser.add_argument("--host", default=settings.HOST, help="服务主机地址")
    parser.add_argument("--port", type=int, default=settings.PORT, help="服务端口")
    parser.add_argument("--debug", action="store_true", help="调试模式")
    parser.add_argument("--log-level", default=settings.LOG_LEVEL, help="日志级别")
    parser.add_argument("--setup-models", action="store_true", help="设置模型后退出")
    
    args = parser.parse_args()
    
    # 设置日志
    setup_logging(args.log_level)
    
    # 如果需要设置模型
    if args.setup_models:
        from models.model_manager import ModelManager
        manager = ModelManager()
        manager.setup_models()
        return
    
    # 检查模型是否存在
    print("🔍 检查模型状态...")
    from local_model_cache import cache_manager
    model_status = cache_manager.verify_all_models_available()
    available_count = sum(model_status.values())
    total_count = len(model_status)
    
    if available_count < total_count:
        missing_models = [name for name, available in model_status.items() if not available]
        print(f"\n❌ 模型检查失败: {available_count}/{total_count} 个模型可用")
        print(f"缺失模型: {', '.join(missing_models)}")
        print("\n请运行以下命令下载模型:")
        print("python download_models.py --download")
        print("\n或者运行以下命令查看详细信息:")
        print("python download_models.py --info")
        return
    
    print(f"✅ 所有模型检查通过 ({available_count}/{total_count})")
    
    # 设置离线模型环境
    from local_model_cache import setup_offline_models
    if not setup_offline_models():
        print("❌ 离线模型环境设置失败")
        return
    
    # 启动服务
    uvicorn.run(
        "app.main:app",
        host=args.host,
        port=args.port,
        reload=args.debug,
        log_level=args.log_level.lower()
    )

if __name__ == "__main__":
    main()